<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php
class MediasController extends AppController {

	var $name = 'Medias';
	var $models = array ('Media');
	var $components = array ('Xmldomparser');
	var $uses = array('Media', 'MediaPlanSlot', 'MediaInfo', 'MediaCacheInfo', 'MediaCode', 'Trip');

	function checkFileSystemPermission() {
		
		$mediaCacheRoot = realpath(ROOT.'/../').'/mediacache/';
		if (!file_exists($mediaCacheRoot) || !is_dir($mediaCacheRoot)) {
			$this->Session->setFlash('No media cache folder found.', 'message_error');
			$this->redirect('/pages/generic_error');
			exit(0);
		}
		//chmod($mediaCacheRoot, 0777);
		if (!is_readable($mediaCacheRoot) || !is_writable($mediaCacheRoot)) {
			$this->Session->setFlash("Please check access permission to media cache directory '".$mediaCacheRoot."'.", 'message_error');
			$this->redirect('/pages/permission_error');
			exit(0);
		}
		
	}
	
	function index() {
		
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		list($order, $limit, $page) = $this->setupPagination();
		$conditions = array('(Media.id != 1 AND Media.id != 2)');
		$medias = $this->Media->findAll($conditions, NULL, $order, $limit, $page );
		if (is_array($medias)) {
			$missingFiles = array();
			foreach ($medias as $key => $media) {
				$mediaCode       = $media['Media']['media_code']; 
				$mediaVendorCode = $media['MediaVendor']['media_vendor_code'];
				$xmlFile = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode."/media-meta.xml";
				if (file_exists($xmlFile)) {
					$this->Xmldomparser->loadFile($xmlFile);
					$medias[$key]['Media']['media_text_latest_version']  = $this->Xmldomparser->getLatestVersion($xmlFile, "text");
					$medias[$key]['Media']['media_image_latest_version'] = $this->Xmldomparser->getLatestVersion($xmlFile, "image"); 
					$medias[$key]['Media']['media_audio_latest_version'] = $this->Xmldomparser->getLatestVersion($xmlFile, "audio"); 
					$medias[$key]['Media']['media_video_latest_version'] = $this->Xmldomparser->getLatestVersion($xmlFile, "video");
					 
					$medias[$key]['Media']['media_text_start_version']  = $this->Xmldomparser->getStartVersion($xmlFile, "text");
					$medias[$key]['Media']['media_image_start_version'] = $this->Xmldomparser->getStartVersion($xmlFile, "image"); 
					$medias[$key]['Media']['media_audio_start_version'] = $this->Xmldomparser->getStartVersion($xmlFile, "audio"); 
					$medias[$key]['Media']['media_video_start_version'] = $this->Xmldomparser->getStartVersion($xmlFile, "video"); 
				} else {
					$medias[$key]['Media']['media_text_latest_version']  = '-';
					$medias[$key]['Media']['media_image_latest_version'] = '-'; 
					$medias[$key]['Media']['media_audio_latest_version'] = '-'; 
					$medias[$key]['Media']['media_video_latest_version'] = '-'; 
					$missingFiles[] = $xmlFile; 
					continue;
				}
			}
		}
		if (count($missingFiles) > 0) {
			$fileMissingMessage = "Following meta file(s) containing media version information are missing <br />"; 
			$this->Session->setFlash($fileMissingMessage, 'message_error');
		}
		$this->set('medias', $medias);
		$this->set('missingFiles', $missingFiles);
	}
	
	function search() {
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$searchFields = array(
			'media_code'=>"Code",
			'media_title'=>"Title",
			'media_duration'=>"Duration"
		);
		$searchOrder = array('ASC'=>"Ascending", 'DESC'=>"Descending");
		if(empty($this->data)) {
			list($order, $limit, $page) = $this->setupPagination();
			$conditions = array('(Media.id != 1 AND Media.id != 2)');
			$medias = $this->Media->findAll($conditions, NULL, $order, $limit, $page );
			if(is_array($medias)) {
				foreach($medias as $key => $media){
					$mediaCode       = $media['Media']['media_code']; 
					$mediaVendorCode = $media['MediaVendor']['media_vendor_code'];
					$xmlFile = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode."/media-meta.xml";
					$this->Xmldomparser->loadFile($xmlFile);
					$medias[$key]['Media']['media_text_latest_version']  = $this->Xmldomparser->getLatestVersion($xmlFile, "text");
					$medias[$key]['Media']['media_image_latest_version'] = $this->Xmldomparser->getLatestVersion($xmlFile, "image"); 
					$medias[$key]['Media']['media_audio_latest_version'] = $this->Xmldomparser->getLatestVersion($xmlFile, "audio"); 
					$medias[$key]['Media']['media_video_latest_version'] = $this->Xmldomparser->getLatestVersion($xmlFile, "video"); 
				}
			}
			$this->set('medias', $medias);
			$this->set('searchOrder', $searchOrder);
			$this->set('searchFields', $searchFields);
		} else {
			//debug($this->data);
			list($order, $limit, $page) = $this->setupPagination();
			$conditions = array();
			$fields = array();
			if ($this->data['Media']['search_fields'] && isset($this->data['Media']['search_fields_select'])) {
				foreach ($this->data['Media']['search_fields_select'] as $fileld) {
					$fields[] = $fileld;
				}
			} else {
				$fields = NULL;
			}
			if($this->data['Media']['search_order'] && isset($this->data['Media']['search_order_select'])) {
				if($this->data['Media']['search_order_direction'] == 'ASC' ){
					$order = 'Media.'.$this->data['Media']['search_order_select'] . ' ASC';
				} else {
					$order = 'Media.'.$this->data['Media']['search_order_select'] . ' DESC';
				}
			}
			if($this->data['Media']['search_key'] && isset($this->data['Media']['search_key_select'])) {
				$conditions = array('Media.'.$this->data['Media']['search_key_select'] . " LIKE '%".$this->data['Media']['search_key_value']."%'");
			}
			//debug($conditions);
			$medias = $this->Media->findAll($conditions, $fields, $order, $limit, $page );
			$this->set('medias', $medias);
			$this->set('searchOrder', $searchOrder);
			$this->set('searchFields', $searchFields);
		}
	}

	function view($id = null) {
		
		$this->checkRecordExistance($id);
		$this->set('media', $this->Media->read(null, $id));
		
	}

	function add() {
		
		$this->checkFileSystemPermission();
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		if (empty($this->data)) {
			
			if (!is_array($mediaVendors = $this->Media->MediaVendor->generateList(NULL, 'media_vendor_name ASC'))) {
				$mediaVendors = array();
			}
			if (!is_array($mediaCategories = $this->Media->MediaCategory->generateList(NULL, 'media_category_name ASC'))) {
				$mediaCategories = array();
			}
			$this->data['Media']['media_duration']="00:00:00";
			$this->set('mediaVendors', $mediaVendors);
			$this->set('mediaCategories', $mediaCategories);
			$this->render();
			
		} else {
			
			$this->data['Media']['media_code'] = low($this->data['Media']['media_code']);
			$this->cleanupData();
			$this->Media->begin(); 
			$this->MediaCode->begin(); 
			$this->MediaInfo->begin(); 
			$this->MediaCacheInfo->begin();
			$allowCommit = true;
			
			if ($this->Media->save($this->data)) {
				// File upload secion
				$mediaVendorCode = $this->Media->MediaVendor->field('media_vendor_code', "id =".$this->data['Media']['media_vendor_id']);
				$mediaCode       = $this->data['Media']['media_code'];
				$mediaId         = $this->Media->getLastInsertID();			
				
				// Save media code to media_codes table
				
				$mediaCodeFields['MediaCode.media_code'] = $mediaCode;
				if (!$this->MediaCode->hasAny($mediaCodeFields)) {
					$mediaCodeData['MediaCode']['media_id']   = $mediaId;
					$mediaCodeData['MediaCode']['media_code'] = $mediaCode;
					if (!$this->MediaCode->save($mediaCodeData)) {
						$allowCommit = false;
						$this->Session->setFlash('Error wile updating media code list.', 'message_error');
					}
				} else {
					$allowCommit = false;
					$this->Session->setFlash('Media code already exists in media codes list.', 'message_error');
				}
				
				$targetFolder = $mediaCacheRoot.$mediaVendorCode;
				if (!file_exists($targetFolder)) { 
					mkdir($targetFolder);
					chmod($targetFolder, 0777);
				} 
				$targetFolder = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode;
				if (file_exists($targetFolder)) { 
					if (!$this->deleteTree($targetFolder)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while writing file system.', 'message_error');
					}
				}
				$xmlFile = $targetFolder."/media-meta.xml";
				if (!file_exists($targetFolder)) { 
					mkdir($targetFolder);
					mkdir($targetFolder.'/text');
					mkdir($targetFolder.'/image');
					mkdir($targetFolder.'/audio');
					mkdir($targetFolder.'/video');
					chmod($targetFolder, 0777);
					chmod($targetFolder.'/text', 0777);
					chmod($targetFolder.'/image', 0777);
					chmod($targetFolder.'/audio', 0777);
					chmod($targetFolder.'/video', 0777);
					$this->Xmldomparser->createFile($xmlFile);
					chmod($xmlFile, 0777);
				}
				if (!empty($this->data['Media']['media_text'])) {
					$this->Media->saveField('media_text_active_version', 1);
					$extension = "txt";
					$target = $targetFolder."/text/".'1.'.$extension;
					file_put_contents($target, $this->data['Media']['media_text']);
					chmod($target, 0777);
					$this->Xmldomparser->addVersion($xmlFile, "text", $extension, "Active");
					if (!$this->pushToMediaCacheInfoQueue($target)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating media cache info queue.', 'message_error');
					}
				} else if (!empty($this->params['form']) && is_uploaded_file($this->params['data']['Media']['media_image']['tmp_name'])) {
					$this->Media->saveField('media_image_active_version', 1);
					$path_parts = pathinfo($this->params['data']['Media']['media_image']['name']);
					$extension  = $path_parts['extension'];
					$target     = $targetFolder."/image/".'1.'.$extension;
					if (move_uploaded_file($this->params['data']['Media']['media_image']['tmp_name'], $target)) {
						// File uploaded
						chmod($target, 0777);
						$this->Xmldomparser->addVersion($xmlFile, "image", $extension, "Active");
						if (!$this->pushToMediaCacheInfoQueue($target) ) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating media cache info queue.', 'message_error');
						}
					}
				} else if (!empty($this->params['form']) && is_uploaded_file($this->params['data']['Media']['media_audio']['tmp_name'])) {
					$this->Media->saveField('media_audio_active_version', 1);
					$path_parts = pathinfo($this->params['data']['Media']['media_audio']['name']);
					$extension = $path_parts['extension'];
					$target = $targetFolder."/audio/".'1.'.$extension;
					if (move_uploaded_file($this->params['data']['Media']['media_audio']['tmp_name'], $target)) {
						// File uploaded
						chmod($target, 0777);
						$this->Xmldomparser->addVersion($xmlFile, "audio", $extension, "Active");
						if (!$this->pushToMediaCacheInfoQueue($target)) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating media cache info queue.', 'message_error');
						}
					}
				} else if (!empty($this->params['form']) && is_uploaded_file($this->params['data']['Media']['media_video']['tmp_name'])) {
					$this->Media->saveField('media_video_active_version', 1);
					$path_parts = pathinfo($this->params['data']['Media']['media_video']['name']);
					$extension = $path_parts['extension'];
					$target = $targetFolder."/video/".'1.'.$extension;
					if (move_uploaded_file($this->params['data']['Media']['media_video']['tmp_name'], $target)) {
						// File uploaded
						chmod($target, 0777);
						$this->Xmldomparser->addVersion($xmlFile, "video", $extension, "Active");
						if (!$this->pushToMediaCacheInfoQueue($target)) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating media cache info queue.', 'message_error');
						}
					}
				}
				// End File upload secion
				if (!$this->pushToMediaInfoQueue("media", $mediaId)) {
					$allowCommit = false;
					$this->Session->setFlash('Error while updating media info queue.', 'message_error');
				}
				
				if ($allowCommit) {
					$this->Media->commit(); 
					$this->MediaCode->commit(); 
					$this->MediaInfo->commit(); 
					$this->MediaCacheInfo->commit(); 
					$this->Session->setFlash('New Media has been added.', 'message_ok');
					$this->redirect('/medias/index');
					
				} else {
					$this->Media->rollback(); 
					$this->MediaCode->rollback(); 
					$this->MediaInfo->rollback(); 
					$this->MediaCacheInfo->rollback(); 
					if (!is_array($mediaVendors = $this->Media->MediaVendor->generateList(NULL, 'media_vendor_name ASC'))) {
						$mediaVendors = array();
					}
					if (!is_array($mediaCategories = $this->Media->MediaCategory->generateList(NULL, 'media_category_name ASC'))) {
						$mediaCategories = array();
					}
					$this->set('mediaVendors', $mediaVendors);
					$this->set('mediaCategories', $mediaCategories);
				}
				
			} else {
				$this->Media->rollback(); 
				$this->MediaInfo->rollback(); 
				$this->MediaCacheInfo->rollback(); 
				$this->Session->setFlash('Please correct errors below.', 'message_error');
				if (!is_array($mediaVendors = $this->Media->MediaVendor->generateList(NULL, 'media_vendor_name ASC'))) {
					$mediaVendors = array();
				}
				if (!is_array($mediaCategories = $this->Media->MediaCategory->generateList(NULL, 'media_category_name ASC'))) {
					$mediaCategories = array();
				}
				$this->set('mediaVendors', $mediaVendors);
				$this->set('mediaCategories', $mediaCategories);
			}
		}
		
	}

	function edit($id = null, $confirm = null, $autoContent = false) {
		
		if ($id == 1 || $id == 2) {
			$this->Session->setFlash('Special type Media, No editing allowed', 'message_error');
			$this->redirect('/medias/index');
			exit(0);
		}
		
		$this->checkFileSystemPermission();
		if ($confirm === null){
			$this->confirm_edit($id);
			exit(0);
		} else if ($confirm === 0) {
			$this->Session->setFlash('Operation cancelled by user.', 'message_ok');
			$this->redirect('/medias/index');
			exit(0);
		} else {
			$this->MediaPlanSlot->begin();
			$this->MediaInfo->begin(); 
	
			$this->MediaPlanSlot->recursive = 3;
			if (!is_array($mediaPlanSlots = $this->MediaPlanSlot->findAll(array('MediaPlanSlot.media_id' => $id)))) {
				$mediaPlanSlots = array();
			}
			$routeSchedules = array(); 
			foreach ($mediaPlanSlots as $mediaPlanSlot) {
				$routeScheduleId   = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['id'];
				$routeScheduleCode = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['route_schedule_code'];
				if(!array_key_exists($routeScheduleId, $routeSchedules)) {
					$routeSchedules[$routeScheduleId] = $routeScheduleCode; 			
				}
			}
			
			$allowCommit = true; 
			// Delete All Media slot entries with media id = $id
			foreach ($mediaPlanSlots as $mediaPlanSlot) {
				if (!$autoContent) {	// Donot delete the media slots if the POST is from automatic content generator
					if (!$this->MediaPlanSlot->del($mediaPlanSlot['MediaPlanSlot']['id'])) {
						$allowCommit = false; 
					}
				}
			}
			
			foreach ($routeSchedules as $routeScheduleId => $routeScheduleCode) {
				// Create a media info entry only if route schedule is assigned to any vehicle
				if ($this->Trip->findCount(array('Trip.route_schedule_id'=>$routeScheduleId)) > 0) {
					if(!$this->pushToMediaInfoQueue('media_plan', $routeScheduleId)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating media infos queue.', 'message_error');
					}
				}
			}
			
			if ($allowCommit) {
				$this->MediaPlanSlot->commit();
				$this->MediaInfo->commit();
			} else {
				$this->MediaPlanSlot->rollback();
				$this->MediaInfo->rollback();
				$this->Session->setFlash('Error while updating media plans.', 'message_error');
				$this->redirect('/medias/index');
				exit(0);
			}
		}
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		if(empty($this->data)) {
			$this->checkRecordExistance($id);
			$this->data = $this->Media->read(null, $id);
			if(!is_array($mediaCategories = $this->Media->MediaCategory->generateList(NULL, 'media_category_name ASC'))){
				$mediaCategories = array();
			}
			$mediaVendorCode = $this->Media->MediaVendor->field('media_vendor_code', "id =".$this->data['Media']['media_vendor_id']);
			$this->set('mediaCategories', $mediaCategories);
			$this->set('mediaVendorCode', $mediaVendorCode);
			$this->render("edit");
		} else {
			// To prevent media vendor/ code modification by any malpractice
			$this->data['Media']['media_vendor_id'] = $this->Media->field('media_vendor_id', "Media.id =".$id);
			$this->data['Media']['media_code'] = $this->Media->field('media_code', "Media.id =".$id);
			$this->cleanupData();
			$this->Media->begin(); 
			$this->MediaInfo->begin(); 
			$this->MediaCacheInfo->begin(); 
			$allowCommit = true;
			if($this->Media->save($this->data)) {
			// File upload secion
				$mediaVendorCode = $this->Media->MediaVendor->field('media_vendor_code', "id =".$this->data['Media']['media_vendor_id']);
				$mediaCode       = $this->data['Media']['media_code'];
				$targetFolder    = $mediaCacheRoot.$mediaVendorCode;
				if (!file_exists($targetFolder)){
					mkdir($targetFolder);
					chmod($targetFolder, 0777);
				}
				$targetFolder = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode;
				$xmlFile = $targetFolder."/media-meta.xml";
				if (!file_exists($targetFolder)){ 
					mkdir($targetFolder);
					mkdir($targetFolder.'/text');
					mkdir($targetFolder.'/image');
					mkdir($targetFolder.'/audio');
					mkdir($targetFolder.'/video');
					chmod($targetFolder, 0777);
					chmod($targetFolder.'/text', 0777);
					chmod($targetFolder.'/image', 0777);
					chmod($targetFolder.'/audio', 0777);
					chmod($targetFolder.'/video', 0777);
				}
				if (!empty($this->data['Media']['media_text'])) {
					$newVersion = $this->Xmldomparser->getNewVersion($xmlFile, "text");
					$extenstion = "txt";
					$target = $targetFolder."/text/".$newVersion.'.'.$extenstion;
					file_put_contents($target, $this->data['Media']['media_text']);
					chmod($target, 0777);
					$this->Xmldomparser->addVersion($xmlFile, "text", $extenstion, "Active");
					if (!$this->pushToMediaCacheInfoQueue($target)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating media cache info queue.', 'message_error');
					}
				} else if (!empty($this->params['form']) && is_uploaded_file($this->params['data']['Media']['media_image']['tmp_name'])) {
					$newVersion = $this->Xmldomparser->getNewVersion($xmlFile, "image");
					$path_parts = pathinfo($this->params['data']['Media']['media_image']['name']);
					$extenstion = $path_parts['extension'];
					$target = $targetFolder."/image/".$newVersion.'.'.$extenstion;
					if (move_uploaded_file($this->params['data']['Media']['media_image']['tmp_name'], $target)) {
						// File uploaded
						chmod($target, 0777);
						$this->Xmldomparser->addVersion($xmlFile, "image", $extenstion, "Active");
						if (!$this->pushToMediaCacheInfoQueue($target)) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating media cache info queue.', 'message_error');
						}
					}
				} else if (!empty($this->params['form']) && is_uploaded_file($this->params['data']['Media']['media_audio']['tmp_name'])) {
					$newVersion = $this->Xmldomparser->getNewVersion($xmlFile, "audio");
					$path_parts = pathinfo($this->params['data']['Media']['media_audio']['name']);
					$extenstion = $path_parts['extension'];
					$target = $targetFolder."/audio/".$newVersion.'.'.$extenstion;
					if (move_uploaded_file($this->params['data']['Media']['media_audio']['tmp_name'], $target)) {
						// File uploaded
						chmod($target, 0777);
						$this->Xmldomparser->addVersion($xmlFile, "audio", $extenstion, "Active");
						if (!$this->pushToMediaCacheInfoQueue($target)) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating media cache info queue.', 'message_error');
						}
					}
				} else if (!empty($this->params['form']) && is_uploaded_file($this->params['data']['Media']['media_video']['tmp_name'])) {
					$path_parts = pathinfo($this->params['data']['Media']['media_video']['name']);
					$extenstion = $path_parts['extension'];
					$newVersion = $this->Xmldomparser->getNewVersion($xmlFile, "video");
					$target = $targetFolder."/video/".$newVersion .'.'.$extenstion;
					if (move_uploaded_file($this->params['data']['Media']['media_video']['tmp_name'], $target)) {
						// File uploaded
						chmod($target, 0777);
						$this->Xmldomparser->addVersion($xmlFile, "video", $extenstion, "Active");
						if (!$this->pushToMediaCacheInfoQueue($target)) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating media cache info queue.', 'message_error');
						}
					}
				}
				// End File upload secion
				
				// Change Active version field in database
				
				$versionData['Media']['id']                         = $id;
				$versionData['Media']['media_text_active_version']  = $this->Xmldomparser->getActiveVersion($xmlFile, "text");
				$versionData['Media']['media_image_active_version'] = $this->Xmldomparser->getActiveVersion($xmlFile, "image");
				$versionData['Media']['media_audio_active_version'] = $this->Xmldomparser->getActiveVersion($xmlFile, "audio");
				$versionData['Media']['media_video_active_version'] = $this->Xmldomparser->getActiveVersion($xmlFile, "video");
				$fields = array('media_text_active_version', 'media_image_active_version', 'media_audio_active_version', 'media_video_active_version');
				if (!$this->Media->save($versionData, false, $fields)) {
					$allowCommit = false;
					$this->Session->setFlash('Error while updating media version.', 'message_error');
				}
				
				// End of Active version section
				
				if (isset($this->data['Media']['media_has_active_text_version'])) {
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'text',  'Active');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'image', 'Inactive');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'audio', 'Inactive');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'video', 'Inactive');
					$this->Media->saveField('media_has_active_image_version', 0);
					$this->Media->saveField('media_has_active_audio_version', 0);
					$this->Media->saveField('media_has_active_video_version', 0);
				} else if (isset($this->data['Media']['media_has_active_image_version'])) {
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'text',  'Inactive');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'image', 'Active');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'audio', 'Inactive');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'video', 'Inactive');
					$this->Media->saveField('media_has_active_text_version',  0);
					$this->Media->saveField('media_has_active_audio_version', 0);
					$this->Media->saveField('media_has_active_video_version', 0);
				} else if (isset($this->data['Media']['media_has_active_audio_version'])) {
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'text',  'Inactive');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'image', 'Inactive');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'audio', 'Active');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'video', 'Inactive');
					$this->Media->saveField('media_has_active_text_version',  0);
					$this->Media->saveField('media_has_active_image_version', 0);
					$this->Media->saveField('media_has_active_video_version', 0);
				} else if (isset($this->data['Media']['media_has_active_video_version'])) {
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'text',  'Inactive');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'image', 'Inactive');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'audio', 'Inactive');
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'video', 'Active');
					$this->Media->saveField('media_has_active_text_version',  0);
					$this->Media->saveField('media_has_active_image_version', 0);
					$this->Media->saveField('media_has_active_audio_version', 0);
					$this->Xmldomparser->changeMediaStatus($xmlFile, 'text', 'Inactive');
				}
				
				// Updating media slots table
				if (!$this->updateMediaPlanSlots($id, $this->data['Media']['media_duration'])) {
					$allowCommit = false;
					$this->Session->setFlash('Error while updating media plan slots.', 'message_error');
				}
				
				if (!$this->pushToMediaInfoQueue("media", $id)) {
					$allowCommit = false;
					$this->Session->setFlash('Error while updating media info queue.', 'message_error');
				}
				
				if ($allowCommit) {
					$this->Media->commit(); 
					$this->MediaInfo->commit(); 
					$this->MediaCacheInfo->commit(); 
					$this->Session->setFlash('The Media has been saved.', 'message_ok');
					$this->redirect('/medias/index');
				} else {
					$this->Media->rollback(); 
					$this->MediaInfo->rollback(); 
					$this->MediaCacheInfo->rollback(); 
					if (!is_array($mediaCategories = $this->Media->MediaCategory->generateList(NULL, 'media_category_name ASC'))) {
						$mediaCategories = array();
					}
					$mediaVendorCode = $this->Media->MediaVendor->field('media_vendor_code', "id =".$this->data['Media']['media_vendor_id']);
					$this->set('mediaCategories', $mediaCategories);
					$this->set('mediaVendorCode', $mediaVendorCode);
				}
			} else {
				$this->Media->rollback(); 
				$this->MediaInfo->rollback(); 
				$this->MediaCacheInfo->rollback(); 
				$this->Session->setFlash('Please correct errors below.', 'message_error');
				if (!is_array($mediaCategories = $this->Media->MediaCategory->generateList(NULL, 'media_category_name ASC'))) {
					$mediaCategories = array();
				}
				$mediaVendorCode = $this->Media->MediaVendor->field('media_vendor_code', "id =".$this->data['Media']['media_vendor_id']);
				$this->set('mediaCategories', $mediaCategories);
				$this->set('mediaVendorCode', $mediaVendorCode);
			}
		}
		
	}

	function delete($id = null, $confirm = null) {
		
		if ($id == 1 || $id == 2) {
			$this->Session->setFlash('Special type Media, Deletion not allowed', 'message_error');
			$this->redirect('/medias/index');
			exit(0);
		}
		
		if ($confirm === null) {
			$this->confirm_delete($id);
			exit(0);
		} else if ($confirm === 0) {
			$this->Session->setFlash('Operation cancelled. Media not deleted.', 'message_ok');
			$this->redirect('/medias/index');
			exit(0);
		}
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$this->checkRecordExistance($id);
		$media = $this->Media->read(null, $id);
		$mediaVendorCode = $media['MediaVendor']['media_vendor_code'];
		$mediaCode       = $media['Media']['media_code'];
		$targetFolder    = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode;
		$this->Media->begin();
		$this->MediaCode->begin();
		$this->MediaInfo->begin();
		$this->MediaCacheInfo->begin();
		$this->MediaPlanSlot->recursive = 3;
		$allowCommit = true; 
		if (!$this->refreshMediaCacheInfoQueue($mediaVendorCode."/".$mediaCode)) {
			$allowCommit = false;
			$this->Session->setFlash('Error while updating media cache info queue, Media not deleted.', 'message_error');
		}
		if (!$this->refreshMediaInfoQueue('media', $id)) {
			$allowCommit = false;
			$this->Session->setFlash('Error while updating media info queue, Media not deleted.', 'message_error');
		}
		
		if (!is_array($mediaPlanSlots = $this->MediaPlanSlot->findAll(array('MediaPlanSlot.media_id' => $id)))) {
			$mediaPlanSlots = array();
		}
		$routeSchedules = array();
		 
		foreach ($mediaPlanSlots as $mediaPlanSlot) {
			$routeScheduleId   = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['id'];
			$routeScheduleCode = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['route_schedule_code'];
			if(!array_key_exists($routeScheduleId, $routeSchedules)) {
				$routeSchedules[$routeScheduleId] = $routeScheduleCode; 			
			}
		}
		
		foreach ($routeSchedules as $routeScheduleId => $routeScheduleCode) {
			// Create a media info entry only if route schedule is assigned to any vehicle
			if ($this->Trip->findCount(array('Trip.route_schedule_id'=>$routeScheduleId)) > 0) {
				if(!$this->pushToMediaInfoQueue('media_plan', $routeScheduleId)) {
					$allowCommit = false;
					$this->Session->setFlash('Error while updating route scheule infos queue.', 'message_error');
				}
			}
		}
		
		$mediaCode = $this->Media->field('media_code', array("Media.id" => $id));
		if ($this->Media->del($id)) {
			$mediaCodeListEntry = $this->MediaCode->find(array("MediaCode.media_id" => $id));
			$mediaCodeListEntry['MediaCode']['media_deleted'] = 1;
			if ($this->MediaCode->save($mediaCodeListEntry)) {
				if (!$this->deleteTree($targetFolder)) { 
					$allowCommit = false;
					$this->Session->setFlash('Filesystem error.', 'message_error');
				}
			} else {
				$allowCommit = false;
				$this->Session->setFlash('Error while upadating media code list.', 'message_error');
			}
		} else {
			$allowCommit = false;
			$this->Session->setFlash('Unable to delete record.', 'message_error');
		}
		if ($allowCommit) {
			$this->Media->commit(); 
			$this->MediaCode->commit(); 
			$this->MediaInfo->commit();
			$this->MediaCacheInfo->commit();
			$this->Session->setFlash('Media deleted.', 'message_ok');
			$this->redirect('/medias/index');
			exit(0);
		} else {
			$this->Media->rollback(); 
			$this->MediaCode->rollback(); 
			$this->MediaInfo->rollback(); 
			$this->MediaCacheInfo->rollback(); 
			$this->showError(ERROR_DELETE, 'Unable to delete files.');
		}
		
	}
	
	function confirm_delete($id) {
		
		if (empty($this->data)) {
			$this->set('media_id', $id);
			$this->set('media_title', $this->Media->field('Media.media_title', "Media.id =".$id));
			$this->MediaPlanSlot->recursive = 3;
			if (!is_array($mediaPlanSlots = $this->MediaPlanSlot->findAll(array('MediaPlanSlot.media_id' => $id)))) {
				$mediaPlanSlots = array();
			}
			$routeSchedules = array(); 
			foreach ($mediaPlanSlots as $mediaPlanSlot) {
				$routeScheduleId   = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['id'];
				$routeScheduleCode = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['route_schedule_code'];
				if(!array_key_exists($routeScheduleId, $routeSchedules)) {
					$routeSchedules[$routeScheduleId] = $routeScheduleCode; 			
				}
			}
			if (count($routeSchedules) == 0) {
				$this->delete($id, 1);
				exit(0);
			}		
			$this->set('routeSchedules', $routeSchedules);
			$this->render('confirm_delete');
			exit(0);
		} else {
			if ($this->data['Media']['confirm']) {
				$this->delete($id, 1);
				exit(0);
			} else {
				$this->delete($id, 0);
				exit(0);
			}
		}
		
	}
	
	function confirm_edit($id) {
		
		if (empty($this->data)) {
			$this->set('media_id', $id);
			$this->set('media_title', $this->Media->field('Media.media_title', "Media.id =".$id));
			$this->MediaPlanSlot->recursive = 3;
			if (!is_array($mediaPlanSlots = $this->MediaPlanSlot->findAll(array('MediaPlanSlot.media_id' => $id)))) {
				$mediaPlanSlots = array();
			}
			$routeSchedules = array(); 
			foreach ($mediaPlanSlots as $mediaPlanSlot) {
				$routeScheduleId   = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['id'];
				$routeScheduleCode = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['route_schedule_code'];
				if(!array_key_exists($routeScheduleId, $routeSchedules)) {
					$routeSchedules[$routeScheduleId] = $routeScheduleCode; 			
				}
			}
			if (count($routeSchedules) == 0) {
				$this->edit($id, 1);
				exit(0);
			}		
			$this->set('routeSchedules', $routeSchedules);
			$this->render('confirm_edit');
			exit(0);
		} else {
			$this->checkJavaScript();
			if($this->data['Media']['confirm']){
				unset($this->data);
				$this->edit($id, 1);
				exit(0);
			} else {
				$this->edit($id, 0);
				exit(0);
			}
		}
		
	}
	
	function edit_versions($id, $mediaType) {
		
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$mediaCode = $this->Media->field('Media.media_code', "Media.id =".$id);
		$mediaVendorCode = $this->Media->field('MediaVendor.media_vendor_code', "Media.id =".$id);
		$xmlFile = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode."/media-meta.xml";
		if (file_exists($xmlFile)) {
			if (!is_array($info = $this->Xmldomparser->getAllVersions($mediaType, $xmlFile))) {
				$info = array();
			}
			$this->set('versionInfo', $info);
		}
		$this->set('mediaId', $id);
		$this->set('mediaType', $mediaType);
		$this->set('updateDiv', $mediaType."MediaVersions");
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		$this->render('edit_versions', 'ajax');
		
	}
	
	function view_versions($id, $mediaType) {
		
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$mediaCode = $this->Media->field('Media.media_code', "Media.id =".$id);
		$mediaVendorCode = $this->Media->field('MediaVendor.media_vendor_code', "Media.id =".$id);
		$xmlFile = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode."/media-meta.xml";
		if (file_exists($xmlFile)) {
			if (!is_array($versionInfo = $this->Xmldomparser->getAllVersions($mediaType, $xmlFile))) {
				$versionInfo = array();
			}
			$this->set('versionInfo', $versionInfo);
		}
		$this->set('mediaId', $id);
		$this->set('mediaType', $mediaType);
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		$this->render('view_versions', 'ajax');
		
	}
	
	function activate_version($id, $mediaType, $version) {
		
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$mediaCode       = $this->Media->field('Media.media_code', "Media.id =".$id);
		$mediaVendorCode = $this->Media->field('MediaVendor.media_vendor_code', "Media.id =".$id);
		$xmlFile = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode."/media-meta.xml";
		
		$this->Media->begin(); 
		$this->MediaInfo->begin();
		$allowCommit = true;
		$oldVersion = $this->Xmldomparser->getActiveVersion($xmlFile, $mediaType);
		$info = $this->Xmldomparser->changeVersion($xmlFile, $id, $mediaType, $version);
		$this->data['Media']['id'] = $id;
		$activeVersion = $this->Xmldomparser->getActiveVersion($xmlFile, $mediaType);
		if (!$this->pushToMediaInfoQueue('media', $id)) {
			$allowCommit = false;
		}
		$mediaVersionField = 'media_'.$mediaType.'_active_version';
		$this->data['Media'][$mediaVersionField] = $activeVersion;
		if (!$this->Media->save($this->data, false, array($mediaVersionField))) {
			$allowCommit = false;
		}
		if ($allowCommit) {
			$this->Media->commit(); 
			$this->MediaInfo->commit();
		} else {
			//	Rollback to previous version;
			$this->Xmldomparser->changeVersion($xmlFile, $id, $mediaType, $oldVersion);
			$this->Media->rollback(); 
			$this->MediaInfo->rollback();
			$this->Session->setFlash('Error while activating media version.', 'message_error');
		}
		header("Cache-Control: no-cache");
		header("Pragma: no-cache"); 
		$this->redirect('/medias/edit_versions/'.$id.'/'.$mediaType);
		
	}
	
	function download_version($id, $mediaType, $version) {
		
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$mediaCode = $this->Media->field('Media.media_code', "Media.id =".$id);
		$mediaVendorCode = $this->Media->field('MediaVendor.media_vendor_code', "Media.id =".$id);
		$xmlFile = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode."/media-meta.xml";
		
		switch ($mediaType) {
			case 'text':
				$extension = $this->Xmldomparser->getMediaVersionExtension($xmlFile, $mediaType, $version);
				$contentType = "text/plain";
				break;
			case 'image':
				$extension = $this->Xmldomparser->getMediaVersionExtension($xmlFile, $mediaType, $version);
			//	$contentType = "image/png";
				break;
			case 'audio':
				$extension = $this->Xmldomparser->getMediaVersionExtension($xmlFile, $mediaType, $version);
			//	$contentType = "audio/mpeg";
				break;
			case 'video':
				$extension = $this->Xmldomparser->getMediaVersionExtension($xmlFile, $mediaType, $version);
			//	$contentType = "video/mpg";
				break;
		}
		$file = $mediaCacheRoot.$mediaVendorCode.'/'.$mediaCode.'/'.$mediaType.'/'.$version.'.'.$extension;
		$downloadName = basename($file);  
		
		if (file_exists($file)) { 
			$fp = fopen($file, "rb");
		//	header("Content-Type: " . $contentType);
			header("Content-Disposition: attachment; filename=" . $downloadName);
		//	header("Content-Length: " . filesize($file));
			fpassthru($fp);	
			fclose($fp);	
			$this->render('download_version', 'ajax');
			exit(0);
		} else {
			$this->Session->setFlash('File cannot be opened', 'message_error');
			$this->redirect('/pages/media_not_found');
		}
		
	}
		
	function view_multiple($id = null) {
		$flag = true;
		if (isset($this->params['url']['ids'])) {
			$ids = explode(";", $this->params['url']['ids']);
			if (count($ids) > 0) {
				foreach ($ids as $id) {
					if ($id != null) {
						$id = intval($id); 
						unset($fields);
						$fields['Media.id'] = $id;
						if ($this->Media->hasAny($fields)) {
							$validIds[] = $id; 
						}
					} 
				}
				if (isset($validIds)) {
					$idList       = implode(",", $validIds);
					$conditions   = array("Media.id IN ($idList)");
					$medias       = $this->Media->findAll($conditions);
				} else {
					$flag = false;
				}
			} else {
				$flag = false;
			}
		} else {
			$flag = false;
		}
		if ($flag) {
			$this->set('medias', $medias);
		} else {
			$this->Session->setFlash('No Media selected to view.', 'message_error');
			$this->redirect('/medias/index');
		}
	}
	
	
	function updateMediaPlanSlots($mediaId, $mediaDuration) {
		
		$flag = true;
		
		if (!is_array($mediaPlanSlots = $this->MediaPlanSlot->findAll(array('MediaPlanSlot.media_id' => $mediaId)))) {
			$mediaPlanSlots = array();
		}
		$duartionData['MediaPlanSlot']['media_plan_slot_duration'] = $mediaDuration;
		foreach ($mediaPlanSlots as $mediaPlanSlot) {
			$duartionData['MediaPlanSlot']['id'] =  $mediaPlanSlot['MediaPlanSlot']['id'];
			$fields = array('media_plan_slot_duration');
			if (!$this->MediaPlanSlot->save($duartionData, false, $fields)) {
				$flag = false;
			}
		}
		return $flag;
	}

	/**
	 * Pushes a new entry to the media infos queue   
	 * Do nothing if an entry with same info type and reference already exists
	 */
	function pushToMediaInfoQueue($infoType, $referenceId) {
		
		$fields['media_info_type'] = $infoType; 
		$fields['media_info_reference'] = $referenceId;
		if ($this->MediaInfo->hasAny($fields)) {
			// Entry already exists; Just return
			return true;
		}
		$data['MediaInfo']['id']                   = null;
		$data['MediaInfo']['media_info_type']      = $infoType;
		$data['MediaInfo']['media_info_reference'] = $referenceId;
		if ($this->MediaInfo->save($data)) {
			return true;
		} else {
			return false;
		}
		 
	}
	
	/**
	 * If a reference id is present delete it.
	 * Else create a new reference
	 */
	function refreshMediaInfoQueue($type, $id) {
		
		$fields['MediaInfo.media_info_type']      = $type; 
		$fields['MediaInfo.media_info_reference'] = $id;
		if ($this->MediaInfo->hasAny($fields)) {
			$mediaInfoId = $this->MediaInfo->field('MediaInfo.id', $fields);
			return $this->MediaInfo->del($mediaInfoId);
		} else {
			return $this->pushToMediaInfoQueue($type, $id);
		}
		/*
		$mediaPlanSlots = $this->MediaPlanSlot->findAll(array('MediaPlanSlot.media_id' => $id), 'DISTINCT MediaPlanSlot.media_plan_id');
		if (is_array($mediaPlanSlots) && count($mediaPlanSlots)>0) {
			foreach ($mediaPlanSlots as $mediaPlanSlot) {
				$this->pushToMediaInfoQueue("media_plan", $mediaPlanSlot['MediaPlanSlot']['media_plan_id']);
			}
		}
		*/
		
	}
	
	function pushToMediaCacheInfoQueue($location) {
		
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache').DS;
		$location       = str_replace($mediaCacheRoot, "/", $location);
		$mediaCacheRoot = str_replace('\\', "/", $location);
		//$data['MediaCacheInfo']['id'] = null;
		$data['MediaCacheInfo']['media_cache_info_location'] = $location;
		if ($this->MediaCacheInfo->save($data)) {
			return true;
		} else {
			return false;
		}
		
		  // Remove all queue entries older than .....
		  
		  /*
		  $currentTimeStamp = date("Y-m-d H:i:s");;
		  $mark = $currentTimeStamp = $someValue;
		  $updates = $this->MediaInfo->findAll('timestamp' < $mark', 'id');
		  foreach($updates as $update){
			  echo $update['Media']['id'];
		  }
		  */
	}
	
	function refreshMediaCacheInfoQueue($path) {
		/*
		if($this->data['Media']['search_key'] && isset($this->data['Media']['search_key_select'])) {
			}
			//debug($conditions);
		*/
		$conditions = array("MediaCacheInfo.media_cache_info_location LIKE '%".$path."%'");
		$fields = 'MediaCacheInfo.id';
		if(!(is_array($mediaCacheInfos = $this->MediaCacheInfo->findAll($conditions, $fields)))) {
			$mediaCacheInfos = array();
		}
		foreach($mediaCacheInfos as $mediaCacheInfo) {
			 if (!$this->MediaCacheInfo->del($mediaCacheInfo['MediaCacheInfo']['id'])) {
			 	return false;
			 }
		}
		return true;
	}
	
	/**
	 * This will delete a directory and its' contents.
	 * @param string $path Path to the target folder to be deleted
	 */
	function deleteTree($path) {
		$mediaCacheRoot = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$flag = true;
		if (is_dir($path)){
			$entries = scandir($path);
			foreach ($entries as $entry) {
				if ($entry != '.' && $entry != '..') {
					if (!$this->deleteTree($path.DS.$entry)){
						$flag = false;
					}
		  		}
			}
			if (!rmdir($path)){
				$flag = false;
			}
	 	} else {
	 		if (file_exists($path)){
				if (!unlink($path)){
					$flag = false;
				}
			}
			// Now if a reference to this file exists in media_cache_info queue, delete it also.
			$mediaCacheRoot = str_replace('\\', "/", $mediaCacheRoot);
			$path           = str_replace('\\', "/", $path);
			$location       = str_replace($mediaCacheRoot, "/mediacache/", $path);
			$fields['MediaCacheInfo.media_cache_info_location'] = $location; 
			if ($this->MediaCacheInfo->hasAny($fields)){
				$mediaInfoId = $this->MediaCacheInfo->field('MediaCacheInfo.id', $fields);
				$this->MediaCacheInfo->del($mediaInfoId);
			} 
	 	}
		return $flag;
	}
	
	function clean() {
		
		$this->Media->begin(); 
		$this->MediaInfo->begin(); 
		$this->MediaCacheInfo->begin();
		
		$mediaCacheRoot       = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$allowCommit = true;
		
		$conditions = array('(Media.id != 1 AND Media.id != 2)');
		$medias = $this->Media->findAll($conditions);
		foreach ($medias as $key => $media) {
			$mediaId         = $media['Media']['id']; 
			$mediaCode       = $media['Media']['media_code']; 
			$mediaVendorCode = $media['MediaVendor']['media_vendor_code'];
			$targetFolder    = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode;
			$xmlFile         = $targetFolder."/media-meta.xml";
			$this->Xmldomparser->loadFile($xmlFile);
			
			// Remove all old versions from XML file
			$versions = $this->Xmldomparser->getAllVersions('video', $xmlFile);
			
			foreach ($versions as $version) {
				if ($version['status'] == "Inactive") {
					$versionNo = $version['version_no'];
					$extenstion = $this->Xmldomparser->getMediaVersionExtension($xmlFile, "video", $versionNo);
					$this->Xmldomparser->removeVersion($xmlFile, 'video', $versionNo);
					// Remove this versions from file system also
					$targetFile = $targetFolder.'/video/'.$versionNo.'.'.$extenstion;
					if (file_exists($targetFile)){
						if (!unlink($targetFile)){
							$allowCommit = false;
						}
					}
				}
			}
		}
		
		// Update media cache info queue
		if (!$this->cleanMediaCacheInfos()) {
			$allowCommit = false;
			$this->Session->setFlash('Error while cleaning media cache information.', 'message_error');
		}
		
		if ($allowCommit) {
			$this->Session->setFlash('Cleanup success.', 'message_ok');
			$this->Media->commit(); 
			$this->MediaInfo->commit(); 
			$this->MediaCacheInfo->commit(); 
		} else {
			$this->Media-$flag>rollback(); 
			$this->MediaInfo->rollback(); 
			$this->MediaCacheInfo->rollback(); 
		}
		$this->redirect('/medias/index');
		
	}
	
	function clean2() {
		
		$this->Media->begin(); 
		$this->MediaInfo->begin(); 
		$this->MediaCacheInfo->begin();
		
		$allowCommit = true;
		$mediaCacheRoot       = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$defaultMediaDuration = "00:00:01";
		$defaultMediaVersion  = 1;
		$conditions = array('(Media.id != 1 AND Media.id != 2)');
		$medias = $this->Media->findAll($conditions);
		if (is_array($medias) && count($medias)) {
			$missingFiles = array();
			foreach ($medias as $key => $media) {
				$mediaId         = $media['Media']['id']; 
				$mediaCode       = $media['Media']['media_code']; 
				$mediaVendorCode = $media['MediaVendor']['media_vendor_code'];
				$targetFolder    = $mediaCacheRoot.$mediaVendorCode."/".$mediaCode;
				$xmlFile         = $targetFolder."/media-meta.xml";
				$this->Xmldomparser->loadFile($xmlFile);
				$medias[$key]['Media']['media_video_latest_version'] = $this->Xmldomparser->getLatestVersion($xmlFile, "video");
				$media['Media']['media_duration'] = $defaultMediaDuration;
				if($this->Media->save($media)) {
					////
					// upload default video file
					$newVersion = $this->Xmldomparser->getNewVersion($xmlFile, "video");
					
					$extenstion = $this->Xmldomparser->getMediaVersionExtension($xmlFile, "video", $defaultMediaVersion);
					$source     = $targetFolder."/video/".$defaultMediaVersion .'.'.$extenstion;
					$target     = $targetFolder."/video/".$newVersion .'.'.$extenstion;
					
					// Fake File upload
					if (copy($source, $target)) {
						chmod($target, 0777);
						$this->Xmldomparser->addVersion($xmlFile, "video", $extenstion, "Active");
						if (!$this->pushToMediaCacheInfoQueue($target)) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating media cache info queue.', 'message_error');
						}
					}
					// End File upload section
					// Change Active version field in database
				
					$versionData['Media']['id']                         = $mediaId;
					$versionData['Media']['media_text_active_version']  = $this->Xmldomparser->getActiveVersion($xmlFile, "text");
					$versionData['Media']['media_image_active_version'] = $this->Xmldomparser->getActiveVersion($xmlFile, "image");
					$versionData['Media']['media_audio_active_version'] = $this->Xmldomparser->getActiveVersion($xmlFile, "audio");
					$versionData['Media']['media_video_active_version'] = $this->Xmldomparser->getActiveVersion($xmlFile, "video");
					$fields = array('media_text_active_version', 'media_image_active_version', 'media_audio_active_version', 'media_video_active_version');
					if (!$this->Media->save($versionData, false, $fields)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating media version.', 'message_error');
					}
					
					// End of Active version section
					
					
					// create media info entry with info type = 'media'
					if (!$this->pushToMediaInfoQueue("media", $mediaId)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating media info queue.', 'message_error');
					}
					// create media info entry with info type = 'mediaplan'
					$this->MediaPlanSlot->recursive = 3;
					if (!is_array($mediaPlanSlots = $this->MediaPlanSlot->findAll(array('MediaPlanSlot.media_id' => $mediaId)))) {
						$mediaPlanSlots = array();
					}
					$routeSchedules = array(); 
					foreach ($mediaPlanSlots as $mediaPlanSlot) {
						$routeScheduleId   = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['id'];
						$routeScheduleCode = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['route_schedule_code'];
						if(!array_key_exists($routeScheduleId, $routeSchedules)) {
							$routeSchedules[$routeScheduleId] = $routeScheduleCode; 			
						}
					}
		
					foreach ($routeSchedules as $routeScheduleId => $routeScheduleCode) {
						// Create a media info entry only if route schedule is assigned to any vehicle
						if ($this->Trip->findCount(array('Trip.route_schedule_id'=>$routeScheduleId)) > 0) {
							if(!$this->pushToMediaInfoQueue('media_plan', $routeScheduleId)) {
								$allowCommit = false;
								$this->Session->setFlash('Error while updating media infos queue.', 'message_error');
							}
						}
					}
					
					// Updating media slots table
					if (!$this->updateMediaPlanSlots($mediaId, $defaultMediaDuration)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating media plan slots.', 'message_error');
					}
					
					// Remove all other versions expect last
					if (!$this->removeOldMediaVersions($mediaId, $defaultMediaDuration)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while removing old media versions.', 'message_error');
					}
					
					
					// Update media cache info queue
					if (!$this->cleanMediaCacheInfos()) {
						$allowCommit = false;
						$this->Session->setFlash('Error while cleaning media cache information.', 'message_error');
					}
							////
				}
			}
		} else {
			$this->Session->setFlash('Please create some media first.', 'message_error');
			$allowCommit = false;
		}
		
		/*
		if ($allowCommit) {
			$this->Session->setFlash('Clean up operation success.', 'message_ok');
			$allowCommit = false;
		}
		*/
		if ($allowCommit) {
			$this->Media->commit(); 
			$this->MediaInfo->commit(); 
			$this->MediaCacheInfo->commit(); 
		} else {
			$this->Media-$flag>rollback(); 
			$this->MediaInfo->rollback(); 
			$this->MediaCacheInfo->rollback(); 
		}
		$this->redirect('/medias/index');
		
	}
	
	function removeOldMediaVersions() {
		return true;	
	}
	
	function cleanMediaCacheInfos() {
		
		$mediaCacheRoot  = realpath(ROOT.DS.'..'.DS.'mediacache'.DS).DS;
		$mediaCacheInfos = $this->MediaCacheInfo->findAll();
		
		foreach ($mediaCacheInfos as $mediaCacheInfo) {
			$infoId = $mediaCacheInfo['MediaCacheInfo']['id'];
			$mFile  = $mediaCacheRoot.$mediaCacheInfo['MediaCacheInfo']['media_cache_info_location'];
			if (!file_exists($mFile)) {
				if (!$this->MediaCacheInfo->del($infoId)) {
					return false;
				}
			}
		}
		return true;
			
	}
	
}
?>